package widget.badge;

import android.support.annotation.NonNull;


public class BadgeManager {
    private static final BadgeManager instance = new BadgeManager();
    private static final BadgeNode __root = new BadgeNode("_#_@root~", null, null);

    private BadgeManager() {

    }

    public static BadgeManager getInstance() {
        return instance;
    }

    public BadgeNode addRoot(@NonNull String name, IBadge iBadge) {
        return addNode(name, __root, iBadge);
    }

    public BadgeNode addNode(@NonNull String name, @NonNull String parentName, IBadge iBadge) {
        BadgeNode parent = __root.findNode(parentName);
        //查找父节点
        if (parent != null) {
            return addNode(name, parent, iBadge);
        } else {
            throw new RuntimeException("父节点不存在:" + parentName);
        }
    }

    private BadgeNode addNode(@NonNull String name, @NonNull BadgeNode parent, IBadge iBadge) {
        BadgeNode repeat = __root.findNode(name);
        //查重
        BadgeNode rp = repeat != null ? repeat.getParent() : null;
        if (rp != null) {
            if (parent.getName().equals(rp.getName()))
                parent.tree().remove(name);
            else
                throw new RuntimeException("节点[" + name + "]已存在于父节点：[" + rp.getName() + "]");
        }
        BadgeNode node = new BadgeNode(name, iBadge, parent);
        parent.addNode(node);
        return node;
    }

}
